export default {
  data() {
    return {
      apiIsSended: false,
      parentNav: {},
      apiNavList: []
    }
  },

  methods: {
    genTree () {
      for (const nav of this.apiNavList) {
        const navChildren = this.apiNavList.filter(item => item.parentId === nav.pageId)

        if (this.subMenuVisibal) {
          if (navChildren.length > 0) {
            nav.children = navChildren
          }
        }

        if (this.parentId && this.parentId !== '0' && nav.pageId === this.parentId) {
          this.parentNav = nav
        }
      }

      this.apiNavList = this.apiNavList.filter(item => item.parentId === (this.parentId || '0'))
    },

    genNav (item) {
      const roles = item.roles ? item.roles.split(',') : []

      let pageOrgTypes = roles.pop()

      if (pageOrgTypes) {
        if (/^orgTypes-/.test(pageOrgTypes)) {
          pageOrgTypes = pageOrgTypes.replace('orgTypes-', '').split('-')
        } else {
          roles.push(pageOrgTypes)
          pageOrgTypes = []
        }
      } else {
        pageOrgTypes = []
      }

      return {
        ...item,
        id: item.pageId,
        roles,
        pageOrgTypes,
        order: item.order,
        pageId: item.pageId,
        activeText: item.pageId,
        parentId: item.parentId,
        target: item.target || (item.pageType === '4' ? '_blank' : '_self'),
        name: item.navigateName || item.name,
        href: item.href || `./${item.fileName}.html`
      }
    },

    getNavigationFromPage () {
      this.apiNavList = []
      this.apiIsSended = true

      window.axios.post(`${window.$twApp.gateway}/unified-portal/site/query/page`, {
        // siteId: 'r4BYUj40gGUg',
        siteId: this.$siteConfig ? this.$siteConfig.siteId : '',
        showInNavigate: '1'
      }).then((response) => {
        if (response.data.result && response.data.result.length > 0) {
          this.apiNavList = response.data.result.map(item => {
            return this.genNav(item)
          })

          this.apiNavList.sort((a, b) => a.order - b.order)

          this.genTree()
        }
      })
    }
  },

  mounted () {
    // window.axios.defaults.headers = {
    //   'X-Client-Id': 'cb588fd3f6d04cf9bdc0275c4d353e31',
    //   'Access-Token': '22e580e255327a8f0b5b7d3b74aa4289',
    //   'Current-Org-Id': 'TWPAAS1200000001964',
    //   'Tenant-Id': 'BJ00002',
    //   'X-User-Account': 'TWPAAS1200000082262'
    // }

    this.$root.$on('loaded', this.getNavigationFromPage)

    // 当其在一个页面中隐藏然后再显示，这时候页面不会再触发loaded事件，只能手动触发
    setTimeout(() => {
      if (!this.apiIsSended) {
        this.getNavigationFromPage()
      }
    }, 60)
  },

  watch: {
    dataIsFromPortal (val) {
      if (val) {
        this.getNavigationFromPage()
      }
    },

    subMenuVisibal () {
      this.getNavigationFromPage()
    }
  }
}
